package com.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.server.common.QueryPageParam;
import com.server.common.Result;
import com.server.entity.Goods;
import com.server.entity.Orders;
import com.server.entity.Unorder;
import com.server.entity.User;
import com.server.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CrossOrigin
@RestController
@RequestMapping("/unorder")
public class UnorderController {

	@Autowired
	private UnorderService unorderService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private GoodsService goodsService;

	@Autowired
	private MailService mailService;

	@PostMapping("/saveORmodify")
	public Result saveORmodify(@RequestBody Unorder unorder){
		System.out.println(unorder);
		if(unorderService.saveOrUpdate(unorder))
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}
	@PostMapping("/delete")
	public Result delete(@RequestBody Map<String, List<Integer>> requestMap){
		boolean res = true;
		List<Integer> ids = requestMap.get("ids");
		for(Integer id : ids){
			if(id!=null)
				res=res&unorderService.removeById(id);
		}
		if(res)
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/querylike")
	public Result querylike(@RequestBody QueryPageParam query) {
		// 创建分页对象
		Page<Unorder> page = new Page<>(query.getPageNum(), query.getPageSize());

		// 获取查询参数
		HashMap<String, Object> map = query.getParam();

		// 创建条件构造器
		LambdaQueryWrapper<Unorder> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		// 动态拼接条件
		String id = map.get("id") != null ? map.get("id").toString().trim() : "";
		String uid = map.get("uid") != null ? map.get("uid").toString().trim() : "";
		String gid = map.get("gid") != null ? map.get("gid").toString().trim() : "";
		String time = map.get("time") != null ? map.get("time").toString().trim() : "";
		if (!id.isEmpty()) {
			lambdaQueryWrapper.eq(Unorder::getId, id);
		}
		if (!uid.isEmpty()) {
			lambdaQueryWrapper.eq(Unorder::getUid, uid);
		}
		if (!gid.isEmpty()) {
			lambdaQueryWrapper.eq(Unorder::getGid, gid); // 精确查询
		}
		if (!time.isEmpty()) {
			lambdaQueryWrapper.like(Unorder::getTime, time);
		}
		// 执行查询
		IPage<Unorder> res = unorderService.pageC(page, lambdaQueryWrapper);

		// 返回结果
		return Result.suc(res.getRecords(), res.getTotal());
	}
	@PostMapping("/userquerylike")
	public Result userquerylike(@RequestBody QueryPageParam query) {
		// 创建分页对象
		Page<Unorder> page = new Page<>(query.getPageNum(), query.getPageSize());

		// 获取查询参数
		HashMap<String, Object> map = query.getParam();

		// 创建条件构造器
		LambdaQueryWrapper<Unorder> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		// 动态拼接条件
		String id = map.get("id") != null ? map.get("id").toString().trim() : "";
		String uid = map.get("uid") != null ? map.get("uid").toString().trim() : "";
		String gid = map.get("gid") != null ? map.get("gid").toString().trim() : "";
		String time = map.get("time") != null ? map.get("time").toString().trim() : "";
		if (!id.isEmpty()) {
			lambdaQueryWrapper.eq(Unorder::getId, id);
		}
		if (!uid.isEmpty()) {
			lambdaQueryWrapper.eq(Unorder::getUid, uid);
		}
		if (!gid.isEmpty()) {
			lambdaQueryWrapper.eq(Unorder::getGid, gid); // 精确查询
		}
		if (!time.isEmpty()) {
			lambdaQueryWrapper.like(Unorder::getTime, time);
		}
		// 执行查询
		IPage<Unorder> res = unorderService.pageC(page, lambdaQueryWrapper);
		List<Unorder> dataList = res.getRecords();
		Map<String, String> nameList = new HashMap<>();
		for (Unorder unorder : dataList) {
			String gid1 = String.valueOf(unorder.getGid()); // 获取商品ID
			String name = goodsService.getById(unorder.getGid()).getName(); // 获取商品名称
			nameList.put(gid1, name); // 将商品ID和名称存入 Map 中
		}
		Map<String, Object> data = new HashMap<>();
		data.put("dataList", dataList);
		data.put("namemap", nameList);

		// 返回结果
		return Result.suc(data, res.getTotal());
	}

	@PostMapping("/pay")
	public Result pay(@RequestBody Map<String, List<Integer>> requestMap){
		List<Integer> ids = requestMap.get("ids");
		List<Unorder> unorders = new ArrayList<>();
		List<Goods> goods = new ArrayList<>();
		for(Integer id : ids){
			unorders.add(unorderService.getById(id));
		}
		User user= userService.getById(unorders.get(0).getUid());
		for(Unorder unorder : unorders){
			goods.add(goodsService.getById(unorder.getGid()));
		}
		BigDecimal price = BigDecimal.ZERO;
		for(int i=0;i<ids.size();i++){
			price = price.add(goods.get(i).getPrice().multiply(BigDecimal.valueOf(unorders.get(i).getNum())));
		}
		if(user.getBalance().compareTo(price) >= 0){
			user.setBalance(user.getBalance().subtract(price));
			userService.updateById(user);
			for(Unorder unorder : unorders){
				ordersService.save(Orders.makeOrders(unorder));
			}

			String subject="感谢您的购买！";
			String body="以下订单已完成：\n";
			for(int i=0;i<ids.size();i++){
				body=body+goods.get(i).getName()+"\t*"+unorders.get(i).getNum()+"\t"
						+goods.get(i).getPrice().multiply(BigDecimal.valueOf(unorders.get(i).getNum()))+"元\n";
			}
			body=body+"合计："+price;
			for(Integer id : ids){
				unorderService.removeById(id);
			}
			mailService.sendSimpleMail(user.getEmail(),subject,body);
			return Result.suc(user, 1L);
		}
		else
			return Result.fail();
	}
}
